package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.pojo.TbGoods;
import com.dongdong.pojo.TbGoodsDesc;
import com.dongdong.pojo.TbItem;
import com.dongdong.service.GoodsDescService;
import com.dongdong.service.GoodsService;
import com.dongdong.service.ItemService;
import com.dongdongshop.service.ItemPageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItemPageServiceImpl implements ItemPageService {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

//    dubbo远程调用
    @Reference
    private GoodsService goodsService;

    @Reference
    private GoodsDescService goodsDescService;

    @Reference
    private ItemService itemService;

    @Override
    public void item(Long goodsId) {
//        获取configuration对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter fileWriter = null;
        try {
//        创建模板对象
            Template template = configuration.getTemplate("item.ftl");
//            创建map
            Map map = new LinkedHashMap();

            TbGoodsDesc goodsDesc = goodsDescService.selectId(goodsId);

            TbGoods tbGoods = goodsService.selectId(goodsId);

            List<TbItem> itemList = itemService.selectIdAndStu(goodsId);

            map.put("goods", tbGoods);
            map.put("goodsdesc",goodsDesc);
            map.put("itemList",itemList);

//            创建输出流
            fileWriter = new FileWriter("E:\\itempage\\"+goodsId+".html");
//            输出页面
            template.process(map,fileWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(fileWriter != null){
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
